<template>
  <div class="login-container">
    <el-card class="login-card">
      <h1>欢迎登录 {{ projectStore.getProjectName }}</h1>
      <h2>登录</h2>

      <el-form
        :model="loginForm"
        :rules="loginRules"
        ref="loginFormRef"
        class="login-form"
        @submit.prevent="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            clearable
            show-password
          />
        </el-form-item>

        <el-form-item prop="role" v-if="false"> <!-- 隐藏身份选择项 -->
          <el-select v-model="loginForm.role" placeholder="请选择身份">
            <el-option
              v-for="role in roleStore.roles"
              :key="role.value"
              :label="role.label"
              :value="role.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="loading" native-type="submit" style="width: 100%">
            登录
          </el-button>
        </el-form-item>

        <el-form-item>
          <el-link type="primary" @click="$router.push('/register')">没有账号？去注册</el-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/api/user';
import { useRoleStore } from '@/stores/project/role';
import { useProjectStore } from '@/stores/project/project';
import { User, Lock } from '@element-plus/icons-vue';
import { usePathConfigStore } from '@/stores/project/path-config';

const router = useRouter();
const route = useRoute();

const userStore = useUserStore();
const roleStore = useRoleStore();
const projectStore = useProjectStore();
const pathConfigStore = usePathConfigStore();

const loginFormRef = ref(null);
const loading = ref(false);

const loginForm = ref({
  username: '',
  password: '',
  role: '',
});

const loginRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  role: [{ required: true, message: '请选择身份', trigger: 'change' }],
};

const handleLogin = async () => {
  if (!loginFormRef.value) return;
  try {
    await loginFormRef.value.validate();
    loading.value = true;

    await userStore.login(loginForm.value.username, loginForm.value.password);
    ElMessage.success('登录成功');

    const userRole = userStore.user?.role;
    if (userRole === 'STUDENT') {
      router.push(pathConfigStore.getFrontstageHomePath);
    } else if (userRole === 'TEACHER') {
      router.push(pathConfigStore.getBackstageHomePath);
    } else if (userRole === 'MANAGER') {
      router.push(pathConfigStore.getBackstageHomePath);
    } else {
      ElMessage.error('未知用户角色');
      return;
    }

  } catch (error) {
    ElMessage.error(error.message || '登录失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  // 由主页跳转过来时，自动填充身份选择框
  const roleFromQuery = route.query.role as string;
  // 从 roleStore 获取所有有效的角色值
  const validRoleValues = roleStore.roles.map(r => r.value);

  if (roleFromQuery && validRoleValues.includes(roleFromQuery)) {
    loginForm.value.role = roleFromQuery;
  }
});
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

h1 {
  text-align: center;
  margin-bottom: 10px;
  font-size: 24px;
  color: #409eff;
}

h2 {
  text-align: center;
  margin-bottom: 20px;
}
</style>